<template>
  <el-form ref="ruleFormRef" style="max-width: 80%" :model="ruleForm" :rules="rules" label-width="15%">
    <el-form-item label="年级：" prop="level">
      <el-select v-model="ruleForm.level" placeholder="年级" size="large" style="width: 240px;margin:0 10px;" filterable
        clearable>
        <el-option v-for="item in slevel" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="学科：" prop="subjectId">
      <el-select v-model="ruleForm.subjectId" placeholder="学科" size="large" style="width: 240px;margin:0 10px;"
        filterable clearable>
        <el-option v-for="item in subjectName" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="试卷类型：" prop="paperType">
      <el-select v-model="ruleForm.paperType" placeholder="选择类型" size="large" style="width: 240px;margin:0 10px;"
        filterable clearable>
        <el-option v-for="item in paperType" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="时间限制：" prop="limitDateTime" v-if="ruleForm.paperType == 4">
      <el-date-picker v-model="ruleForm.limitDateTime" type="datetimerange" start-placeholder="开始日期"
        end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
        style="width: 60%;" size="large" />
    </el-form-item>
    <el-form-item label="试卷名称：" prop="name">
      <el-input v-model="ruleForm.name" style="width: 100%" placeholder="请输入试卷名称" size="large" />
    </el-form-item>
    <div>
      <el-form-item :label="`标题${i + 1}:`" prop="titleItems" v-for="(item, i) in ruleForm.titleItems" :key="i">
        <div style="width: 100%;">
          <el-input v-model="item.name" style="width: 80%" placeholder="请输入标题" size="large" />
          <a href="#" @click="addquest(i)">添加标题</a>
          <a href="#" @click="deltitle(i)">删除</a>
        </div>
        <el-card style="width: 100%;margin-top: 20px;" v-for="(quest, index) in item.questionItems" :key="quest.id">
          <div style="width: 15%;float: left;line-height: 80px;font-weight: bolder;">题目{{ index + 1 }}</div>
          <div style="width: 75%;float: left;">
            <p v-html="quest.title"></p>
            <p>
              <span v-for="select in quest.items" style="margin-right: 20px;"
                v-html="`${select.prefix}、${select.content}`"></span>
            </p>
          </div>
          <a href="#" style="line-height: 80px;" @click="delquest(i, index)">删除 </a>
        </el-card>
      </el-form-item>
    </div>

    <el-form-item label="建议时长：" prop="suggestTime">
      <el-input v-model="ruleForm.suggestTime" style="width: 100%" placeholder="请输入时长" size="large" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button type="success" @click="addtitle">添加标题</el-button>
    </el-form-item>
  </el-form>

  <el-dialog v-model="dialogFormVisible" width="50%">
    <el-form :model="form">
      <div style="display: flex;align-items: center;">
        <h5>ID:</h5>
        <el-input v-model="data.id" style="width: 240px;margin:0 10px;" placeholder="请输入题目Id" clearable />
        <h5>题型：</h5>
        <el-select v-model="data.questionType" placeholder="请选择题型" style="width: 240px;margin:0 10px;" filterable
          clearable>
          <el-option label="请选择" value="" />
          <el-option v-for="item in questType" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
        <el-button type="primary" @click="getList">查询</el-button>
      </div>
      <el-table :data="list" border style="width: 100%" :row-key="getRowKey" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column prop="id" label="Id" width="55" />
        <el-table-column prop="questionType" label="题型" width="85" />
        <el-table-column prop="shortTitle" label="题干" />
      </el-table>
      <div style="display: flex; align-items: center;height: 60px;">
        <span>共{{ total }}条</span>
        <div style="margin: 0 20px;">
          <el-select v-model="data.pageSize" placeholder="Select" size="small" style="width: 100px"
            @change="handleSizeChange">
            <el-option v-for="item in psize" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <el-pagination background layout="prev, pager, next" :total="total" @current-change="handleCurrentChange"
          :current-page="data.pageIndex" :page-sizes="[5, 10, 20, 30, 50]" :page-size="data.pageSize" />
        <div style="display: flex;width: 150px;justify-content: center;align-items: center;">
          <span style="display: flex;width: 60px;justify-content: center;align-items: center;">前往</span><el-input
            v-model.lazy="data.pageIndex" class="center-input" style="width: 50px;" /><span
            style="margin-left: 15px;">页</span>
        </div>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="getSelectedData">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, watch, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router';
import { subject, edit, quest, search, add } from "@/api/paper"
// const { locale } = useLocale();
const route = useRoute();
const router = useRouter()
const id: any = route.query.id
// onMounted(() => {
//   const zhCn = require('element-plus/dist/locale/zh-cn.mjs').default;
//   locale.value = zhCn;
// });
if (id && id.length > 0) {
  edit(id).then(res => {
    console.log(res);
    if (res.status === 200) {
      ruleForm.value = res.data.response
    }
  })
}
var quesyId = 0
function addquest(id: number) {
  dialogFormVisible.value = true
  quesyId = id
  data.value.pageIndex = 1
  getList()
}
function delquest(i: number, id: number) {
  ruleForm.value.titleItems[i].questionItems.splice(id, 1);
}
// 选中数据
type selType = {
  analyze: string
  correct: string
  correctArray: []
  difficult: number
  gradeLevel: number
  id: number
  itemOrder: number
  items: { prefix: string, content: string, score: number, itemUuid: number }[]
  questionType: number
  score: string
  subjectId: number
  title: string
}[]
const selectedRows = ref<selType>([])
// 设置行键（必须，用于唯一标识行）
const getRowKey = (row: { id: number }) => row.id
// 监听选择变化
const handleSelectionChange = (rows: selType) => {
  selectedRows.value = rows
}
function removeHtmlTags(html: string): string {
  if (!html) return '';
  // 匹配所有HTML标签的正则表达式
  return html.replace(/<[^>]+>/g, '');
}
const getSelectedData = () => {
  selectedRows.value.forEach((item: any) => {
    search(item.id).then(res => {
      res.data.response.items.map((i: any) => {
        i.content = removeHtmlTags(i.content)
      })
      ruleForm.value.titleItems[quesyId].questionItems.push(res.data.response);
    })
  })

  dialogFormVisible.value = false
}
const paperType = [
  { id: 1, label: "固定试卷" },
  { id: 4, label: "时段试卷" },
  { id: 6, label: "任务试卷" },
]
const questType = [
  { id: 1, label: '单选题' },
  { id: 2, label: '多选题' },
  { id: 3, label: '判断题' },
  { id: 4, label: '填空题' },
  { id: 5, label: '简答题' },
]
type dataType = {
  id: number | '',
  questionType: number | '';
  pageIndex: number | '';
  pageSize: number | '';
  subjectId: string
}
const data = ref<dataType>({
  id: "",
  questionType: "",
  pageIndex: 1,
  pageSize: 5,
  subjectId: ""
})
type listType = {
  analyzeTextContentId: number,
  correct: string,
  createTime: string,
  createUser: number,
  difficult: number,
  id: number,
  questionType: number,
  score: string,
  shortTitle: string,
  status: number,
  subjectId: number,
  textContentId: number
}[]
let list = ref<listType>([])
function getList() {
  quest(data.value).then(res => {
    if (res.status === 200) {
      list.value = res.data.response.list
      total.value = res.data.response.total
    }
  })
}
getList()
let total = ref(0)

const handleCurrentChange = (page: number) => {
  data.value.pageIndex = page
  getList()
}

// 每页条数变化时触发
const handleSizeChange = (size: number) => {
  data.value.pageSize = size
  data.value.pageIndex = 1 // 重置为第一页
  getList()
}
const dialogFormVisible = ref(false)

const form = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})

function addtitle() {
  ruleForm.value.titleItems.push({
    name: '',
    questionItems: [],
  });
}
function deltitle(i: number) {
  ruleForm.value.titleItems.splice(i, 1);
}
const psize = ref([
  { label: '共5条', value: 5 },
  { label: '共10条', value: 10 },
  { label: '共20条', value: 20 },
  { label: '共30条', value: 30 },
  { label: '共40条', value: 40 },
  { label: '共50条', value: 50 },
])
const slevel = ref([
  { label: '一年级', value: 1 },
  { label: '二年级', value: 2 },
  { label: '三年级', value: 3 },
  { label: '四年级', value: 4 },
  { label: '五年级', value: 5 },
  { label: '六年级', value: 6 },
  { label: '初一', value: 7 },
  { label: '初二', value: 8 },
  { label: '初三', value: 9 },
  { label: '高一', value: 10 },
  { label: '高二', value: 11 },
  { label: '高三', value: 12 },
])
interface RuleForm {
  level: number | ''
  subjectId: number | ''
  paperType: number | ''
  name: string
  suggestTime: number | ''
  id: number | ''
  score: string
  limitDateTime: string[]
  titleItems: {
    name: string,
    questionItems: selType[]
  }[]
}

const ruleFormRef = ref<FormInstance>()
let ruleForm = ref<RuleForm>({
  id: '',
  score: '',
  limitDateTime: [],
  level: '',
  subjectId: '',
  paperType: '',
  name: '',
  suggestTime: '',
  titleItems: []
})
const rules = reactive<FormRules<RuleForm>>({
  level: [{ required: true, message: '请选择年级', trigger: 'blur' },],
  subjectId: [{ required: true, message: '请选择学科', trigger: 'blur', },],
  paperType: [{ required: true, message: '请选择试卷类型', trigger: 'blur', },],
  name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' },],
  titleItems: [{ required: true, message: '请输入标题', trigger: 'blur' },],
  suggestTime: [{ required: true, message: '请输入时长', trigger: 'blur' },],
  limitDateTime: [{ required: true, message: '请选择时间', trigger: 'blur' },],
})
function formatDateRange(dateRange: any[]) {
  if (!Array.isArray(dateRange) || dateRange.length === 0) return [];
  return dateRange.map(date => {
    // 处理 Date 对象
    if (date instanceof Date) {
      return date.toISOString().replace('T', ' ').split('.')[0];
    }
    // 处理字符串
    if (typeof date === 'string') {
      return date.replace('T', ' ').replace('Z', '');
    }
    // 处理可能的对象格式
    if (typeof date === 'object' && date !== null) {
      // 尝试从常见字段中提取日期
      if (date.value instanceof Date) {
        return date.value.toISOString().replace('T', ' ').split('.')[0];
      }
      if (typeof date.value === 'string') {
        return date.value.replace('T', ' ').replace('Z', '');
      }
      if (date.date instanceof Date) {
        return date.date.toISOString().replace('T', ' ').split('.')[0];
      }
      if (typeof date.date === 'string') {
        return date.date.replace('T', ' ').replace('Z', '');
      }
    }
    // 无法处理的类型返回空字符串
    return '';
  });
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 创建表单数据副本
      const formData = { ...ruleForm.value };
      // 只格式化日期范围字段
      formData.limitDateTime = formatDateRange(formData.limitDateTime);
      add(formData).then(res => {
        if (res.status === 200) {
          ElMessage.success('编辑成功')
          setTimeout(() => {
            router.push('paper')
          }, 1500)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
interface optionsType {
  deleted: boolean,
  id: number,
  itemOrder: number,
  level: number,
  levelName: string,
  name: string,
}[]
const sub = ref<{ id: number, label: string, level: number }[]>([])
let subjectName = computed<{ id: number; label: string; level: number; }[]>(() => {
  if (!ruleForm.value.level) return []// 未选择年级时返回空数组
  const selectedLevel = ruleForm.value.level
  return sub.value.filter(subject => subject.level === selectedLevel)
})
watch(() => ruleForm.value.level, () => {
  ruleForm.value.subjectId = ''
})
watch(() => data.value.pageIndex, (newValue, oldValue) => {
  if (!newValue) {
    data.value.pageIndex = oldValue
  } else {
    data.value.pageIndex = newValue;
    getList()
  }

});

subject().then(res => {
  const subject = res.data.response.map((subject: optionsType) => {
    const subjectName = subject ? `${subject.name}(${subject.levelName})` : '未知学科'
    return { id: subject.id, label: subjectName, level: subject.level }
  })
  sub.value = subject
})


</script>

<style scoped>
a {
  color: #6f93ff;
  margin: 0 10px;
}

::v-deep .center-input .el-input__inner {
  text-align: center;
}
</style>